<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  personalTagGroupAdd,
  personalTagGroupInfo,
  personalTagGroupUpdate,
} from '#/api/company/tag/personal';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { tagGroupModalSchema, updateCategorySchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '编辑标签组' : '新增标签组';
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: tagGroupModalSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, type } = modalApi.getData() as {
      id: number | string;
      type: string;
    };
    isUpdate.value = !!id;

    updateCategorySchema(formApi, type);

    if (isUpdate.value && id) {
      const record = await personalTagGroupInfo(id);
      await formApi.setValues(record);
    }

    if (type) {
      await formApi.setValues({ type });
    }
    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // formApi.getValues拿到的是一个readonly对象，不能直接修改，需要cloneDeep
    const data = cloneDeep(await formApi.getValues()) as any;
    await (isUpdate.value
      ? personalTagGroupUpdate(data)
      : personalTagGroupAdd(data));
    console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm />
  </BasicModal>
</template>
